# 导入:
from sqlalchemy import Column, String, create_engine, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# 创建对象的基类:
Base = declarative_base()


def getSession():
    # 初始化数据库连接:
    engine = create_engine('mysql+mysqlconnector://paperless:xHUuCLmUO3VkYFYwvTl3@59.111.94.156:13308/paperless_db')
    # 创建DBSession类型:
    DBSession = sessionmaker(bind=engine)

    # 创建Session:
    session = DBSession()
    return session


# 定义User对象:
class User(Base):
    # 表的名字:
    __tablename__ = 'sys_user'

    # 表的结构:
    userId = Column('user_id', Integer, primary_key=True)
    username = Column('username', String(50))
    nickname = Column('nickname', String(50))
    createTime = Column('create_time', String(50))


def listUser():
    session = getSession()
    # 创建Query查询，filter是where条件，最后调用one()返回唯一行，如果调用all()则返回所有行:
    users = session.query(User).filter(User.userId > '1').limit(20)
    for user in users:
        # 打印类型和对象的name属性:
        print(user.username, user.nickname, user.createTime)
    # 关闭Session:
    session.close()


